/**
 * 模拟API模块
 * 替换原来的后端API调用，使用IndexDB存储
 */

import dataManager from '@/utils/dataManager';
import indexedDBManager from '@/utils/indexedDB';
import { message } from 'antd';

// 用户相关API
export const userLogin = async (data = {}) => {
  try {
    const user = await dataManager.login(data.username, data.password);
    return {
      status: 200,
      message: '登录成功',
      data: {
        uid: user.uid,
        username: user.username,
        avatar: user.avatar,
        background: user.background
      }
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const userRegister = async (data = {}) => {
  try {
    const user = await dataManager.register(data);
    return {
      status: 200,
      message: '注册成功',
      data: {
        uid: user.uid,
        username: user.username,
        avatar: user.avatar,
        background: user.background
      }
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const updateAvatar = async (data = {}) => {
  try {
    const updatedUser = await dataManager.updateUser({ avatar: data.avatar });
    return {
      status: 200,
      message: '头像更新成功',
      data: {
        avatar: updatedUser.avatar
      }
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const updateBackGroud = async (data = {}) => {
  try {
    const updatedUser = await dataManager.updateUser({ background: data.background });
    return {
      status: 200,
      message: '背景更新成功',
      data: {
        background: updatedUser.background
      }
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

// 文件夹相关API
export const openfolder = async (data = {}) => {
  try {
    const folders = await dataManager.getDesktopFolders();
    return {
      status: 200,
      message: '获取成功',
      data: folders
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const updateName = async (data = {}) => {
  try {
    await indexedDBManager.updateFolder(data.fid, { name: data.name });
    return {
      status: 200,
      message: '重命名成功'
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const deleteFolder = async (data = {}) => {
  try {
    await indexedDBManager.deleteFolder(data.fid);
    return {
      status: 200,
      message: '删除成功'
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const addFolder = async (data = {}) => {
  try {
    const currentUser = await dataManager.getCurrentUser();
    if (!currentUser) throw new Error('未登录');

    const folder = await indexedDBManager.createFolder({
      uid: currentUser.uid,
      parentId: data.parentId || 0,
      name: data.name,
      x: data.x || 100,
      y: data.y || 100,
      icon: data.icon || 'folder.png',
      isStatic: data.isStatic || false
    });

    return {
      status: 200,
      message: '创建成功',
      data: folder
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const sortUpdateAllFile = async (data = {}) => {
  try {
    // 更新多个文件的位置
    for (const item of data.files || []) {
      if (item.type === 'folder') {
        await indexedDBManager.updateFolder(item.fid, {
          x: item.x,
          y: item.y
        });
      } else {
        await indexedDBManager.updateFile(item.fid, {
          // 文件位置更新逻辑
        });
      }
    }

    return {
      status: 200,
      message: '排序更新成功'
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

// 图片相关API
export const getBackground = async (data = {}) => {
  try {
    const currentUser = await dataManager.getCurrentUser();
    if (!currentUser) throw new Error('未登录');

    const images = await indexedDBManager.getImagesByUser(currentUser.uid);
    return {
      status: 200,
      message: '获取成功',
      data: images.map(img => ({
        id: img.id,
        name: img.name,
        url: img.data,
        type: img.type
      }))
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

// 博客相关API
export const uploadBase64 = async (data = {}) => {
  try {
    const currentUser = await dataManager.getCurrentUser();
    if (!currentUser) throw new Error('未登录');

    // 保存图片到数据库
    const image = await indexedDBManager.saveImage({
      uid: currentUser.uid,
      name: data.name || 'image',
      data: data.base64,
      type: data.type || 'image/png',
      size: data.size || 0
    });

    return {
      status: 200,
      message: '上传成功',
      data: {
        id: image.id,
        url: image.data
      }
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const updateContent = async (data = {}) => {
  try {
    const currentUser = await dataManager.getCurrentUser();
    if (!currentUser) throw new Error('未登录');

    const blog = await indexedDBManager.createBlog({
      uid: currentUser.uid,
      title: data.title,
      content: data.content
    });

    return {
      status: 200,
      message: '保存成功',
      data: {
        bid: blog.bid,
        title: blog.title,
        content: blog.content
      }
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

export const getBlogContent = async (data = {}) => {
  try {
    const currentUser = await dataManager.getCurrentUser();
    if (!currentUser) throw new Error('未登录');

    const blogs = await indexedDBManager.getBlogsByUser(currentUser.uid);
    return {
      status: 200,
      message: '获取成功',
      data: blogs.map(blog => ({
        bid: blog.bid,
        title: blog.title,
        content: blog.content,
        createdAt: blog.createdAt
      }))
    };
  } catch (error) {
    return {
      status: 400,
      message: error.message
    };
  }
};

// 通用错误处理包装器
export const withErrorHandling = (apiFunction) => {
  return async (data = {}) => {
    try {
      const result = await apiFunction(data);
      return result;
    } catch (error) {
      console.error('API Error:', error);
      message.error(error.message || '操作失败');
      return {
        status: 500,
        message: error.message || '操作失败'
      };
    }
  };
};
